// 创建用户相关小仓库
import { defineStore } from 'pinia'
import { reqLogin, reqLogout, reqUserInfo } from '../../api/user'
import type {
  loginForm,
  loginResponseData,
  userInfoResponseData,
} from '../../api/user/type'
import { userStata } from './types/type'
import { SET_TOKEN, GET_TOKEN, CLEAR_TOKEN } from '../../utils/token'
import { constantRoute } from '../../router/routes'
let useUserStore = defineStore('user', {
  state: (): userStata => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute,
      username: '',
      avatar: '',
    }
  },
  //   异步逻辑
  actions: {
    // 用户登录回调
    async userLogin(data: loginForm) {
      let result: loginResponseData = await reqLogin(data)
      if (result.code === 200) {
        // 由于 pinia|vuex 存储数据其实利用 js 对象
        this.token = result.data as string
        SET_TOKEN(result.data as string)
        // 确保返回成功状态的 promise
        // return 'ok' //??
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    async getUserinfo() {
      let res: userInfoResponseData = await reqUserInfo()
      if (res.code === 200) {
        this.username = res.data.name
        this.avatar = res.data.avatar
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    async logout() {
      let res: any = await reqLogout()
      console.log(2324, res)
      if (res.code === 200) {
        this.token = ''
        this.username = ''
        this.avatar = ''
        CLEAR_TOKEN()
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
  },
  getters: {},
})

export default useUserStore
